<template>
  <div v-loading="searchLoading" class="overview-content">
    <div class="overview-content-search">
      <commonSearch
        v-if="searchOption?.length"
        ref="commonSearchRef"
        v-model:loading="searchLoading"
        :row-num="4"
        :operationSpan="3"
        :option="searchOption"
        @submit="submitSearchFormHandler"
        @reset="submitSearchFormHandler"
      />
    </div>
    <div class="overview-content-btns">
      <fabBtns :isDisableDel="isDisableDel" @add="addHandler" @del="delHandler" @import="importHandler" />
    </div>
    <div ref="fabListTableRef" class="overview-content-table">
      <commonTable
        ref="commonTableRef"
        selection
        indexNeed
        :operationOptions="operationOptions"
        :tableCloumns="tableCloumns"
        :height="scrollbarHeight"
        :axiosApi="queryFabListNew"
        :params="params"
        :header-cell-style="headerCellStyleFn"
        :cell-style="cellStyleFn"
        @selection-change="selectionChangeHandler"
      />
    </div>
    <addDevice v-if="addDeviceVisible" :id="keyId" v-model="addDeviceVisible" :eqpId="eqpId" :type="type" @submit="submitHandler" />
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "list"
});

import { ref, reactive, onMounted, onUnmounted, markRaw } from "vue";
import { useRouter } from "vue-router";
import { PxMessage } from "px-ui";
import { Edit, Delete, Modeling } from "@px-ui/icons-vue";
import commonTable from "@/views/common/components/commonTable/index.vue";
import commonSearch from "@/views/common/components/commonSearch/index.vue";
import fabBtns from "./components/fabBtns.vue";
import addDevice from "./components/addDevice.vue";
import { queryFabListNew, removeFabInfoBatch, removeFabInfo } from "@/api/modules/fab";
import { useSearchOption, useTableCloumns } from "./hooks";
import { useUpdateDomHeight, useCancelUpdateDomHeight } from "@/hooks/useCommon";
import { useRouterStoreHook } from "@/store/modules/router";
import { useMessageBox } from "@/hooks/useCommon";

const router = useRouter();
const routerStore = useRouterStoreHook();

interface Props {
  eqpStatus?: string;
  className?: string;
  area?: string;
  isWarning?: boolean;
}
const props = withDefaults(defineProps<Props>(), { eqpStatus: "", className: "", area: "", isWarning: null });

const searchLoading = ref<boolean>(false);
const gap = 90;
const defaultHeight = 606;
const fabListTableRef = ref<HTMLElement | null>(null);
const commonTableRef = ref<CommonTable.TableRefType>(null);
const commonSearchRef = ref<CommonSearch.SearchFormRefType>(null);

const scrollbarHeight = ref<number>(defaultHeight);
const searchOption = ref<Array<CommonSearch.SearchOption>>(useSearchOption(props.eqpStatus, props.className, props.area, props.isWarning));

const detail = (scope: any) => {
  const {
    row: { eqpId = "" }
  } = scope;
  const path = "/fullScreen/fab/detail";
  const className = routerStore.getSubject;
  const query = { eqpId, className };
  let params = encodeURI(JSON.stringify(query));
  const { href } = router.resolve({ path, query: { params } });
  window.open(href, "_blank");
};

const tableCloumns = ref<Array<CommonTable.TableCloumnsType>>(useTableCloumns(detail));
const params = ref<any>({});

const operationOptions: Array<CommonTable.operationOptionItemType> = [
  {
    content: "详情",
    auth: `${routerStore.subject}_FAB_OVERVIEW_DETAIL`,
    icon: markRaw(Modeling),
    click: (scope: any) => detail(scope)
  },
  {
    content: "编辑",
    auth: `${routerStore.subject}_FAB_OVERVIEW_UPDATE`,
    icon: markRaw(Edit),
    click: (scope: any) => edit(scope.row)
  },
  {
    content: "删除",
    auth: `${routerStore.subject}_FAB_OVERVIEW_DELETE`,
    type: "danger",
    icon: markRaw(Delete),
    click: (scope: any) => del(scope.row.id, scope.row.eqpId)
  }
];

let defaultParams: any = {};
let currentParams: any = {};

const headerCellStyleFn = ({ row, column, rowIndex, columnIndex }) => {
  if (columnIndex === 6 || columnIndex === 7) {
    return { textAlign: "center" };
  } else {
    return {};
  }
};

const cellStyleFn = ({ row, column, rowIndex, columnIndex }) => {
  const { warningTime } = row;
  if (warningTime && columnIndex === 2) {
    return { backgroundColor: "#FF33331F" };
  } else if (columnIndex === 6 || columnIndex === 7) {
    return { textAlign: "center" };
  } else {
    return {};
  }
};

const updateParams = () => {
  params.value = { ...defaultParams, ...currentParams };
};

const submitSearchFormHandler = (form: any) => {
  currentParams = { ...currentParams, ...form };
  updateParams();
};

const delList = reactive([]);
const addDeviceVisible = ref(false);
const type = ref("add");
const keyId = ref<number | string>("");
const eqpId = ref<number | string>("");
const isDisableDel = ref(true);

const addHandler = () => {
  keyId.value = "";
  eqpId.value = "";
  type.value = "add";
  addDeviceVisible.value = true;
};

const delHandler = (flag: boolean) => {
  if (flag) return PxMessage.error("请选择设备！");
  const msg = delList.length > 1 ? "确定删除这些设备吗？" : "确定删除该设备吗？";
  useMessageBox("delete", msg, async () => {
    const params = { ids: delList.map(item => item.id) };
    await removeFabInfoBatch(params);
    commonTableRef.value.clearSelection();
    await commonTableRef.value.queryTableData(null, true);
    PxMessage.success("删除成功！");
  });
};

const importHandler = async () => {
  await commonTableRef.value.queryTableData(null, true);
};

const selectionChangeHandler = val => {
  if (val.length) {
    delList.splice(0);
    delList.push(...val);
  }
  isDisableDel.value = !val.length;
};

const submitHandler = async () => {
  await commonTableRef.value.queryTableData(null, true);
};

const edit = ({ id: keyId_ = "", eqpId: eqpId_ = "" }: any) => {
  keyId.value = keyId_;
  eqpId.value = eqpId_;
  type.value = "edit";
  addDeviceVisible.value = true;
};

const del = (id: number, eqpId: string) => {
  const msg = `确定删除 ${eqpId} 吗？`;
  useMessageBox("delete", msg, async () => {
    await removeFabInfo(id);
    await commonTableRef.value.queryTableData(null, true);
    PxMessage.success("删除成功！");
  });
};

onMounted(async () => {
  await useUpdateDomHeight(scrollbarHeight, fabListTableRef, gap, defaultHeight);
});

onUnmounted(() => useCancelUpdateDomHeight());
</script>
<style scoped lang="scss">
.overview-content {
  box-sizing: border-box;
  padding: 16px;
  background-color: #fff;
  border-radius: 4px;

  .overview-content-btns {
    margin-top: 16px;
  }

  .overview-content-table {
    margin-top: 16px;
  }
}
</style>
